package com.zzy.blog.http.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.zzy.blog.json.jsonlib.JsonTest;
import com.zzy.blog.json.jsonlib.JsonUtils;

/**
 * httpclient传输对象
 * @author eason
 *
 */
public class ClientObject {
	
	private static final String LOING_URL = "http://localhost:8080/SSHDemo/monitor";
	

	public static void main(String[] args) throws ClientProtocolException, IOException {
		HttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(LOING_URL);
		
//		传输byte[]
		setByteArrayEntry(httpost);
		
//		传输inputstream
//		setInputStreamEntity(httpost);
		
		HttpResponse response = client.execute(httpost);
		HttpEntity entity = response.getEntity();
		String responseHtml = EntityUtils.toString(entity);
		System.out.println(responseHtml);
	}

	private static void setByteArrayEntry(HttpPost httpost) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
	    ObjectOutputStream oos = new ObjectOutputStream(baos);
	    oos.writeObject(JsonUtils.getJsonString(JsonTest.school));
	    byte[] buffer = baos.toByteArray();
	    
	    httpost.setEntity(new ByteArrayEntity(buffer));
	}
	
	private static void setInputStreamEntity(HttpPost httpost) throws IOException {
	    
		//把data写到inputStream中，但new InputStreamEntity时候要流的长度，需要额外计算，就算了
//		InputStream inputStream = getInputStream(data);
//	    httpost.setEntity(new InputStreamEntity(inputStream, inputStream.length));
	}

}
